package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 购物车
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;


    /**
     * 添加商品到购物车
     */
    @PostMapping("/add")
    public R addCart(@RequestBody ShoppingCart shoppingCart){
        //A. 获取当前登录用户，为购物车对象赋值  ThreadLocal  = Map
        Long userId = BaseContext.getCurrentId();
        //B. 根据当前登录用户ID 及 本次添加的菜品ID/套餐ID，
        shoppingCart.setUserId(userId);
        //查询购物车数据是否存在  条件  餐品或者套餐名字相同，并且 userId相同
        LambdaQueryWrapper<ShoppingCart> wapper = new LambdaQueryWrapper<>();
        if(shoppingCart.getDishId() != null){
            wapper.eq(ShoppingCart::getDishId,shoppingCart.getDishId());
        }
        if(shoppingCart.getSetmealId() != null){
            wapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        wapper.eq(ShoppingCart::getUserId,shoppingCart.getUserId());

        ShoppingCart sCart = shoppingCartService.getOne(wapper);
        //C. 如果已经存在，就在原来数量基础上加1
        if(sCart != null){ //代表存在
            sCart.setNumber(sCart.getNumber()+1);
            shoppingCartService.updateById(sCart);//更新
            return R.success(sCart);
        }
        //D. 如果不存在，则添加到购物车，数量默认就是1
        shoppingCart.setNumber(1);
        shoppingCartService.save(shoppingCart);//新建
        return R.success(shoppingCart);
    }


    /**
     * 查询登录用户的购物车数据
     * @return
     */
    @GetMapping("/list")
    public R findList(){
        //根据userId来查询出这个用户的所有购物车商品
//A. 获取当前登录用户，为购物车对象赋值  ThreadLocal  = Map
        Long userId = BaseContext.getCurrentId();

        LambdaQueryWrapper<ShoppingCart> wapper = new LambdaQueryWrapper<>();
        wapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> list = shoppingCartService.list(wapper);
        return R.success(list);
    }

    @DeleteMapping("/clean")
    public R clean(){
        //1.获得登录的用户id
        Long userId = BaseContext.getCurrentId();

        //2.根据用户id 删除该用户的所有的购物车数据
        LambdaUpdateWrapper<ShoppingCart> wapper = new LambdaUpdateWrapper<>();

        wapper.eq(ShoppingCart::getUserId,userId);

        shoppingCartService.remove(wapper);

        return R.success("清空成功");
    }

 
 }   